package 约定编程;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author zyl
 * @Description
 * @since 2024/1/24 15:09
 */

public class ProxyBean implements InvocationHandler {

    private Object targe = null;
    private Interceptor interceptor = null;

    public static Object getProxyBean(Object targe, Interceptor interceptor){
        ProxyBean proxyBean = new ProxyBean();
        proxyBean.targe = targe;
        proxyBean.interceptor = interceptor;
        Object proxy = Proxy.newProxyInstance(targe.getClass().getClassLoader(), targe.getClass().getInterfaces(), proxyBean);
        return proxy;

    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {

        boolean exceptionFlag = false;
        Invocation invocation = new Invocation( targe,method,args);
        Object o = null;
            try {
                if (this.interceptor.before()) {
                    o = this.interceptor.around(invocation);
                }else {
                    o = method.invoke(targe,args);
                }
            } catch (InvocationTargetException e) {
                exceptionFlag = true;
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                exceptionFlag = true;
                e.printStackTrace();
            }
            if (exceptionFlag){
                this.interceptor.afterThrowing();
            }else {
                this.interceptor.afterReturning();
                return o;
            }
        return null;
    }
}
